package com.coder.algorithm.leetcode

import com.coder.algorithm.struct.ListNode

/**
 * [21. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)
 *
 * @author yuhus
 * @date: 2022/4/7
 */
object l_0021 {
    fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
        val preHead = ListNode(-1)
        var p1 = list1
        var p2 = list2
        var prev = preHead
        while (p1 != null && p2 != null) {
            if (p1.`val` < p2.`val`) {
                prev.next = p1
                p1 = p1.next

            } else {
                prev.next = p2
                p2 = p2.next
            }
            prev = prev.next!!
        }
        prev.next = p1 ?: p2
        return preHead.next
    }
}